#pragma once
#include <string>
#include <queue>
#include <mutex>
#include <atomic>
#include <thread>
#include <condition_variable>
#include <memory>
#include <functional>
#include "connection.h"

class ConnectionPool
{
public:
    // 单例接口
    static ConnectionPool* getConnectionPool();

    // 获取连接
    std::shared_ptr<Connection> getConnection();

private:
    // 构造 / 析构
    ConnectionPool();
    ~ConnectionPool() = default;

    // 禁止拷贝
    ConnectionPool(const ConnectionPool&) = delete;
    ConnectionPool& operator=(const ConnectionPool&) = delete;

    // 配置加载
    bool loadConfigFile();

    // 后台线程任务
    void produceConnectionTask();   // 生产者
    void scannerConnectionTask();   // 空闲回收

private:
    /* === 配置项 === */
    std::string    _ip;
    unsigned short _port;
    std::string    _username;
    std::string    _password;
    std::string    _dbname;
    int            _initSize;
    int            _maxSize;
    int            _maxIdleTime;
    int            _connectionTimeout;

    std::queue<Connection*> _readQue;   // 只给消费者用
    std::queue<Connection*> _writeQue;  // 只给生产者用
    std::mutex              _mutex;     // 保护队列 + 连接计数
    std::condition_variable _cv;        // 等待 / 通知
    std::atomic_int         _connectionCnt{0};
};
